#include "InMenuState.hpp"

#include "InGameState.hpp"
#include "Game.hpp"
#include "ResourceManager.hpp"

#include <SFML/Graphics.hpp>


InMenuState::InMenuState(Game* game, sf::RenderWindow* window)
    : ::GameState(game, window)
{
    loadTextures();
    loadSprites();
}

InMenuState::~InMenuState()
{
    ResourceManager<sf::Sprite>::instance()->remove("Menu_BG");
}

void
InMenuState::init()
{}

void
InMenuState::reset()
{}

void
InMenuState::handleEvents()
{
    sf::Event event;

    while (window_->pollEvent(event))
    {
        if (event.type == sf::Event::Closed ||
            sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
            window_->close();
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1))
            game_->changeState(InGameState::instance(game_, window_));
    }
}

void
InMenuState::update()
{
    // window_->clear(sf::Color(0, 127, 255));
}

void
InMenuState::render()
{
    window_->draw(*ResourceManager<sf::Sprite>::instance()->get("Menu_BG"));

    window_->display();
}

void
InMenuState::loadSprites() const
{
    auto menu_bg = ResourceManager<sf::Texture>::instance()->get("Menu_BG");
    auto spriteManager = ResourceManager<sf::Sprite>::instance();

    spriteManager->add("Menu_BG", new sf::Sprite(*menu_bg));
}

void
InMenuState::loadTextures() const
{
    sf::Texture* menu_bg = new sf::Texture;

    loadTexture(menu_bg, "resources/Menu_BG.png", "Menu_BG");
}

void
InMenuState::loadTexture(sf::Texture* texture,
                         const std::string& fileName,
                         const std::string& textureName) const
{
    if (texture->loadFromFile(fileName))
        ResourceManager<sf::Texture>::instance()->add(textureName, texture);
    else
        throw Exception("Could not load texture: " + fileName);
}
